package timeline;

import java.io.*;
import java.util.*;
//import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

/**
 * Example application that gets public, user and friend timeline using specified account.<br>
 * Usage: java twitter4j.examples.GetTimelines ID Password
 */
public class GetTimelines {
    /**
     * 
     * Usage: java twitter4j.examples.GetTimelines ID Password
     * @param args String[]
     */
	Util util = null;
	PrintStream  out_msg;
	PrintStream  out_user;
	private static final  String output_root = "../output/timeline/";
	GetTimelines(){
    try{
    	
    	boolean exists = (new File(output_root)).exists();
        if (!exists) 
        {
        	boolean success = (new File(output_root)).mkdir();
	        if (!success) 
	        {
	           System.out.println("Create Directory: " + output_root + "Failed. Exit");
	           System.exit(0);
	         }
        }
    	out_msg = new PrintStream (new FileOutputStream("../output//timeline/TimeLine_msg.txt"));
    	out_user = new PrintStream (new FileOutputStream("../output//timeline/TimeLine_user.txt"));
    	util = Util.getInstance(true);
    	}
        catch(Exception exception) {exception.printStackTrace();}
    }
	
    public static void main(String[] args) {
	    
    	Twitter unauthenticatedTwitter = new Twitter();
        GetTimelines getTimelines = new GetTimelines();
        System.out.println("Showing public timeline.");
      
        //for (int i=1;i<=720; i++) {
        while (1 ==1){
        	//System.out.println("i: "+i);
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssZ");
        String currenttime = sdf.format(cal.getTime());
        
      ///create dir by date

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        String currentdate = sdf2.format(cal.getTime());
        String outputdir = output_root +"/"+currentdate;
        boolean exists = (new File(outputdir)).exists();
        if (!exists) 
        {
        	boolean success = (new File(outputdir)).mkdir();
            if (!success) 
            {
              System.out.println("Create Directory: " + outputdir + "Failed. Exit");
              return;
            }
         }
                
        try{
               List<Status> statuses = unauthenticatedTwitter.getPublicTimeline();
               int j = 1;
            for (Status status : statuses) {
            	String user = status.getUser().getName();
            	String msg = status.getText().replaceAll("[\\s]+"," ");
            	getTimelines.out_user.println(user);
            	getTimelines.out_msg.println(msg);
            	
            	String filename = outputdir+"/"+currenttime+"_"+(j++)+".xml";
            	PrintStream output = new PrintStream (new FileOutputStream(filename));
            	output.println(Status.toString(status.elem));
            	output.close();
            	// wget
            	ArrayList<String> urlList = getTimelines.util.getUrl(msg);
            	Iterator<String> iter = urlList.iterator();
                 
                 while (iter.hasNext())
                 {
                	String url = iter.next();
                	//Date date = sdf.parse(status.getCreatedAt());
                	String info = status.getCreatedAt()+"\t"+user+"\t"+url;
                	Runnable runnable = new WgetRunnable(true, cal.getTime(),info, url,0,0);
                	Thread thread = new Thread(runnable);

                	thread.start();
                	//System.out.println ("main thread");

                 }
            	
            }
        }
        catch (TwitterException te) {
                System.err.println("Failed to get timeline: " + te.getMessage());
            
        }
        catch(Exception exception) {exception.printStackTrace();}
            
        getTimelines.out_msg.flush();
        getTimelines.out_user.flush();
        
        try{ Thread.sleep(61000);}
        catch(Exception exception) {exception.printStackTrace();}
            
     }
      //      getTimelines.out_msg.close();
      //      getTimelines.out_user.close();
        //    System.out.println("Done!");
           
        }

}
